package server;

import client.ClientConfig;
import client.RpcClient;
import client.handle.ClientToCenterInboundHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.handle.DataInboundHandle;
import support.Constans;
import support.RpcContext;
import support.RpcInfo;
import support.anno.Config;
import util.AnnotaionScanner;
import util.NetWorkUtil;
import util.StringUtil;

import java.util.List;

//用于连接注册中心的客户端
public class RpcClientAdapter {
    static Logger logger = LoggerFactory.getLogger(RpcClientAdapter.class);
    RpcClient rpcClient;

    public RpcClientAdapter(RpcClient rpcClient) {
        this.rpcClient = rpcClient;
    }

    public RpcClientAdapter() { }

    public boolean lookUpToCenter(String scanPath) throws ClassNotFoundException {
        List<String> scanner = AnnotaionScanner.scanner2(scanPath, Config.class);
        logger.info("扫描{}结果:{}",scanPath,scanner);
        if(StringUtil.listIsEmpty(scanner) && StringUtil.strIsEmpty(RpcContext.shost) && RpcContext.sport==null){ //没有发现注册中心配置
            logger.info("没有配置注册中心，默认以点对点方式进行调用");
            return false;
        }

        if(scanner.size()>1){
            logger.warn("[警告]发现多个配置,请删除多余配置注解，只取第一个...");
        }

        if(StringUtil.listIsEmpty(scanner)){
            RpcContext.clientConfig = new ClientConfig(RpcContext.shost,RpcContext.sport);
        }else {
            Class<?> aClass = Class.forName(scanner.get(0));
            Config cfg = aClass.getAnnotation(Config.class);
            if (RpcContext.clientConfig == null) {
                RpcContext.clientConfig = new ClientConfig(cfg.centerHostName(), cfg.centerPort());
            }
        }
        rpcClient = new RpcClient(RpcContext.clientConfig.getCenterHost(), RpcContext.clientConfig.getCenterPort(), new ClientToCenterInboundHandle(Constans.SERVER_FLAGE));
        return true;
    }

    //与注册中心建立连接
    public boolean connCenter(){
        try {
            rpcClient.conn();
            logger.info("连接注册中心成功!...");
            return true;
        }catch (Exception e){
            logger.error("连接注册中心失败...,原因:{}",e.getMessage());
            return false;
        }
    }

    public void registeInfo(RpcInfo info,String tkey){
        try {
            RpcInfo clone = (RpcInfo) info.clone();
            String[] split = tkey.split("@");
            String newCLassName = split[0];
            clone.setClassName(newCLassName);

            clone.setHost(CoreServer.benHostAddr);
            clone.setPort(CoreServer.port);
            RpcInfo centerRes = rpcClient.sendToCenter(clone);
            logger.info("注册请求发送成功...返回结果:{}",centerRes);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("服务注册失败...");
        }

    }
}
